package com.sean.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sean.dto.User;
import com.sean.form.UserAddFrom;
import com.sean.service.IUserFacade;

@Controller
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private IUserFacade userFacade;

    @RequestMapping("/user/add.do")
    public ModelAndView registerUser(final UserAddFrom form,
	    HttpServletRequest resq, HttpServletResponse resp) {

	if (logger.isDebugEnabled()) {
	    logger.debug(form);
	}

	List result = userFacade.findUserByName(form.getUserName());
	if (result == null || result.isEmpty()) {
	    User user = new User();
	    user.setUsername(form.getUserName());
	    user.setPassword(form.getPassword());
	    user.setEmail(form.getEmail());
	    User finalUser = this.userFacade.addUser(user);
	    ModelMap modelMap = new ModelMap();
	    modelMap.addAttribute("user", finalUser);
	    ModelAndView mav = new ModelAndView("user/user_manager", modelMap);
	    return mav;
	} else {
	    ModelMap modelMap = new ModelMap();
	    modelMap.addAttribute("msg", form.getUserName() + " is exist!");
	    return new ModelAndView("user/register", modelMap);
	}
    }

    /**
     * How to skip this?
     * 
     * @param resq
     * @param resp
     * @return
     */
    @RequestMapping("/user/new.do")
    public String register(HttpServletRequest resq, HttpServletResponse resp) {
	return "user/register";
    }
}
